'use strict';

const { Service } = require('egg');
const ModelName = 'Staff'
const dayjs = require("dayjs");
class RouterService extends Service {
  getTimeList(value, startTime = '08:30', endTime = '21:30') {
    let timeList = []
    // 计算起止分钟
    const [startHour, startMinute] = startTime.split(':').map(Number)
    const [endHour, endMinute] = endTime.split(':').map(Number)
    const startTotal = startHour * 60 + startMinute
    const endTotal = endHour * 60 + endMinute
    // 每半小时一个时间段
    for (let i = 0; i < 48; i++) {
      let hour = Math.floor(i / 2)
      let minute = i % 2 === 0 ? '00' : '30'
      let timeStr = `${hour < 10 ? '0' + hour : hour}:${minute}`
      let total = hour * 60 + (minute === '00' ? 0 : 30)
      if (total < startTotal || total > endTotal) continue
      timeList.push({
        time: timeStr,
        status: 1,
        statusText: '可预约'
      })
    }
    if (value === dayjs().format('YYYY-MM-DD')) {
      // 如果是今天 过滤timeList中小于现在的时间
      let hour = dayjs().hour()
      let minute = dayjs().minute()
      let nowTime = `${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`
      timeList = timeList.filter(timeItem => {
        let item = timeItem.time
        const startH = parseInt(item.split(':')[0])
        const startM = parseInt(item.split(':')[1])
        const nowH = parseInt(nowTime.split(':')[0])
        const nowM = parseInt(nowTime.split(':')[1])
        if (startH > nowH ) {
          if (startH === nowH + 1) {
            if (nowM > 30 && startM === 0) {
              return false
            } else {
              return  true
            }
          } else {
            if (startH > nowH) {
              return true
            } else {
              if (nowM < 30 && startM === 30) {
                return true
              }
              return false
            }
          }
        }
        return false
      })
    }
    return timeList
  }
  async serveTime(staff_id) {
    let dayList = [
      {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD'), children: []},
      {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD'), children: []},
    ]
    for (let i = 0; i < dayList.length; i++) {
      const dayValue = dayList[i].value
      dayList[i].children = this.getTimeList(dayValue)
    }
    return dayList;
  }
  async login({ phone, password }) {
    // 根据账号查询用户是否存在
    let user = await this.ctx.model[ModelName].findOne({
      where: { phone, audit_status: 2, status: 1, is_del: 0 },
    });
    if (!user) throw new Error('账号不存在');
    // 判断密码是否有误
    const isValid = user.password === password
    if (!isValid) {
      throw new Error('密码错误');
    }
    user = user.dataValues;
    delete user.password;
    return user;
  }

  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where: {
        ...where,
        is_del: 0
      },
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        {
            model: this.ctx.model.City,
        }
      ],
      raw: true
    });
  }

  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where: {
        ...where,
        is_del: 0
      },
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        {
          model: this.ctx.model.City,
        },
        { model: this.ctx.model.OrderGoods },
        { model: this.ctx.model.StaffCollect },
        { model: this.ctx.model.StaffComment },
      ]
    });
  }
  async findOne(id) {
    // 今天已经接的订单
    const todayOrderCount = await this.ctx.model.OrderGoods.findAll({
        where: {
            staff_id: id,
          // 时间是今天
            accept_time: {
                [this.app.Sequelize.Op.gte]: dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            },
          // order_status !== -1 未取消 pay_status === 1
            order_status: {
                [this.app.Sequelize.Op.ne]: -1,
            },
            pay_status: 1,
        }
    })
    const todayFinish = await this.ctx.model.OrderGoods.findAll({
      where: {
        staff_id: id,
        order_status: 4,
      }
    })
    const todayWaitService = await this.ctx.model.OrderGoods.findAll({
      where: {
        staff_id: id,
        // order_status 大于1 小于4
        order_status: {
            [this.app.Sequelize.Op.gt]: 0,
            [this.app.Sequelize.Op.lt]: 4,
        }
      }
    })
    const todayRefund = await this.ctx.model.OrderGoods.findAll({
        where: {
            staff_id: id,
            pay_status: 2,
        }
    })
    // 已完成
    const res =  await this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
      include: [
        {
          model: this.ctx.model.City,
        },
        {
          model: this.ctx.model.OrderGoods,
        },
        { model: this.ctx.model.StaffCollect },
      ],
    });
    if (!res.dataValues) throw new Error('未找到该用户')
    return {
        ...res.dataValues,
        todayOrderCount: todayOrderCount.length,
        todayWaitService: todayWaitService.length,
        todayFinish: todayFinish.length,
      todayRefund: todayRefund.length,
    }
  }

  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {
    if (data.id) {
      await this.ctx.model[ModelName].destroy({ where: { id: data.id } });
    }
    return this.ctx.model[ModelName].create({
      ...data,
      id: undefined
    });
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }

  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }
}

module.exports = RouterService;
